<template>
  <div class="echarts-box">
    <div ref="elRef" id="myEcharts" style="width: 100%" :style="styles"></div>
  </div>
</template>
<script setup lang="ts">
import { isString } from "@/utils/is";
import { propTypes } from "@/utils/propTypes";
import type { EChartsOption } from "echarts";
import echarts from "@/plugins/echarts";
const elRef = ref<ElRef>();
let echartRef: Nullable<echarts.ECharts> = null;

const props = defineProps({
  height: {
    type: String,
    default: propTypes.oneOfType([Number, String]).def("500px"),
  },
  options: {
    type: Object,
    default() {
      return {};
    },
  },
});
watch(
  () => props.options,
  () => {
    setOptions();
  },
  { deep: true }
);

const styles = computed(() => {
  const height = isString(props.height) ? props.height : `${props.height}px`;
  return {
    height,
  };
});
onMounted(() => {
  initChart();
});

const initChart = () => {
  if (unref(elRef) && props.options) {
    echartRef = echarts.init(unref(elRef) as unknown as HTMLElement);
    setOptions();
  }
};

const setOptions = () => {
  if (unref(elRef) && props.options) {
    const _legendData: string[] = [];
    const _seriesData: any = [];
    props.options.seriesData.forEach((item: any) => {
      _legendData.push(item.name);
      _seriesData.push({
        data: item.data,
        name: item.name,
        type: "line",
        smooth: true,
        label: {
          show: true,
          position: "top",
          formatter: "{c}",
        },
      });
    });

    const _echartOption: EChartsOption = {
      title: {
        text: props.options.title,
        left: "left",
      },
      grid: {
        left: "0",
        right: "0",
        bottom: "0",
        containLabel: true,
      },
      legend: {
        data: _legendData,
      },
      xAxis: {
        type: "category",
        data: props.options.xAxisData,
      },
      tooltip: {
        trigger: "axis",
      },
      yAxis: {
        type: "value",
      },
      series: _seriesData,
    };
    echartRef?.setOption(_echartOption);
  }
};
</script>
